<template>
    <el-card shadow="never">
        <div class="edu-page-title">申请明细</div>
        <div class="msg-tip" style="margin-bottom:15px" v-if="defenseType==1&&applyType==0">
            <p>温馨提示：请于预计毕业时间期满前至少三个月提出申请</p>
        </div>
        <el-form
            ref="applyForm"
            :model="applyForm"
            label-width="150px"
            label-suffix="："
            :rules="rules"
        >
            <el-row :gutter="20">
                <el-col :span="8">
                    <el-form-item :label="'预计'+label+'答辩时间'" prop="defenseTime">
                        <el-date-picker
                            v-model="applyForm.defenseTime"
                            type="date"
                            format="yyyy-MM-dd"
                            value-format="yyyy-MM-dd"
                            placeholder="选择日期"
                            style="width:100%"
                            :picker-options="pickerOption"
                        ></el-date-picker>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="20">
                <el-col :span="16">
                    <el-form-item label="原因说明" prop="reasonDesc">
                        <el-input
                            type="textarea"
                            rows="3"
                            v-model="applyForm.reasonDesc"
                            maxlength="200"
                        />
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <!-- 两种情况必填：1.提前答辩 2.延期答辩申请时间超过最长学习年限-->
                <el-col :span="16">
                    <el-form-item label="申请材料" prop="attachFile">
                        <el-upload
                            ref="uploadBtn"
                            id="upload-btn"
                            :data="{bucketname: 'face', folderpath: 'file'}"
                            action="/api/commonservice/obsfile/uploadfile"
                            :auto-upload="false"
                            :on-success="handleUploadSuccess"
                            :on-remove="handleUploadRemove"
                            :on-error="handleUploadError"
                            :on-exceed="handleUploadExceed"
                            :on-change="handleUploadChange"
                            multiple
                            :limit="5"
                            :file-list="fileList"
                        >
                            <div>
                                <el-button size="small" type="primary">上传附件</el-button>
                                <div
                                    v-if="defenseType==0"
                                    slot="tip"
                                    class="el-upload__tip"
                                >上传要求：请上传jpg/png/word/pdf/xls等文件，且不超过5M</div>
                            </div>
                        </el-upload>
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>
        <!-- <div class="msg-tip" v-if="defenseType==0&&applyType==0"> -->
            <div class="msg-tip" v-if="defenseType==0">
            <p>博士需上传附件：已通过的学位论文盲审复印件</p>
            <p>硕士需上传附件：1、学术论文期刊封面、目录及正文首页复印件；2、已通过的学位论文盲审复印件</p>
        </div>
        <div align="right">
            <el-button @click="handleReturn">{{$t('message.return')}}</el-button>
            <el-button v-if="showSaveBtn" type="primary" @click="handleSave">{{$t('message.save')}}</el-button>
            <el-button type="primary" @click="handleSubmit">{{$t('message.submit')}}</el-button>
        </div>
        <edu-dialog
            :title="$t('message.prompt')"
            width="450px"
            :visible.sync="showDialog"
            :showFooter="false"
        >
            <div>返回将不会保存当前填写数据，是否确定？</div>
            <div class="float-right" style="margin:25px 0 0 0">
                <el-button @click="showDialog=false">{{$t("message.cancel")}}</el-button>
                <el-button @click="confirmReturn" type="primary">{{$t("message.confirm")}}</el-button>
                <el-button v-if="showSaveBtn" @click="saveAndClose" type="primary">保存并关闭</el-button>
            </div>
            <div style="clear:both"></div>
        </edu-dialog>
    </el-card>
</template>
<script>
import {
    applyAdvancedOralDefense,
    applyDelayedOralDefense,
    editOralDefense,
    isExceedLimit,
    getLastTermDate
} from "common/src/api/culture/change";
export default {
    name: "ApplyForm",
    props: {
        showSaveBtn: {
            default: false,
            type: Boolean
        },
        students: {
            default: null
        },
        editForm: {
            default: null
        },
        defenseType: {
            default: null //0是提前答辩，1是延期答辩
        },
        applyType: {
            default: null
        },
        submitType: {
            default: null
        },
        mayGraduatTime: {
            default: null
        } 
    },
    data: function() {
        return {
            label: null,
            fileList: [],
            applyForm: {
                defenseTime: null,
                reasonDesc: null,
                attachFile: null
            },
            isDraft: false, //是否草稿
            fileSuccessStatus: "success",
            rules: {
                defenseTime: {
                    required: true,
                    message: "必须填写预计提前答辩时间",
                    trigger: "change"
                },
                reasonDesc: {
                    required: true,
                    message: "必须填写原因说明",
                    trigger: "change"
                },
                pleaseNum: {
                    required: true,
                    message: "必须填写请示文号",
                    trigger: "change"
                },
                attachFile: []
            },
            showDialog: false,
            pickerOption: {
                disabledDate: this.disabledDate  
            },
            endTime: null
        };
    },
    watch: {
        students(val, oldVal) {
            // 延期
            if (this.defenseType != 0) {
                this.applyForm.defenseTime = null
            }
            this.isMaxLengthSchoolingByStudentId();
            this.getLastTermEndTime();
        }
    },
    mounted() {
        //提前答辩，必须上传申请材料
        if (this.defenseType == 0) {
            this.rules.attachFile.push({
                required: true,
                message: "必须上传申请材料",
                trigger: "change"
            });
        }
        this.rules.attachFile.push({
            validator: this.handleFileCheck,
            trigger: "change"
        });

        this.label = this.defenseType == 0 ? "提前" : "延期";
        if (this.editForm) {
            Object.keys(this.applyForm).forEach(key => {
                if (this.editForm.hasOwnProperty(key)) {
                    this.applyForm[key] =
                        typeof this.editForm[key] === "number"
                            ? this.editForm[key].toString()
                            : this.editForm[key];
                    if (key === "defenseTime") {
                        this.applyForm[key] = moment(this.editForm[key]).format(
                            "YYYY-MM-DD"
                        );
                    }
                }
            });
            this.fileList = this.applyForm.attachFile.map(file => {
                    return { name: file.name, url: file.url };
                });
        }
        this.isMaxLengthSchoolingByStudentId();
        this.getLastTermEndTime();
    },
    methods: {
        getLastTermEndTime() {
            if (
                this.defenseType == 0 &&
                this.students &&
                this.students.length == 1
            ) {
                getLastTermDate(
                    this.students[0].studentId,
                    this.students[0].lengthSchooling
                ).then(res => {
                    if (res.code == 200) {
                        this.endTime = res.data;
                    }
                });
            }
        },
        isMaxLengthSchoolingByStudentId() {
            if (this.defenseType == "1" && this.students) {
                let param = this.students.map(student => {
                    return {
                        studentId: student.studentId,
                        maxLengthSchooling: student.maxLengthSchooling
                    };
                });
                isExceedLimit(param).then(res => {
                    if (res.code == 200) {
                        if (res.data) {
                            this.rules.attachFile = [
                                {
                                    required: true,
                                    message: "必须上传申请材料",
                                    trigger: "change"
                                },
                                {
                                    validator: this.handleFileCheck,
                                    trigger: "change"
                                }
                            ];
                            //超过最长学习年限，当前时间加6个月
                            let now = new Date();
                            now.setMonth(now.getMonth() + 6);
                            this.endTime = now.getTime();
                        } else {
                            this.rules.attachFile = [
                                {
                                    validator: this.handleFileCheck,
                                    trigger: "change"
                                }
                            ];
                            //未超过最长学习年限，时间为入学年月+最长学习年限
                            if (
                                this.students[0].enrolDate &&
                                this.students[0].maxLengthSchooling
                            ) {
                                let end = new Date(this.students[0].enrolDate);
                                //enrolDate格式为2019-10，需初始化日时分秒
                                end.setDate(1);
                                end.setHours(0);
                                end.setMinutes(0);
                                //最长学习年限可能是正数，也可能是小数
                                let maxLengthSchooling = Number(
                                    this.students[0].maxLengthSchooling
                                );
                                let year = Math.floor(maxLengthSchooling);
                                end.setFullYear(end.getFullYear() + year);
                                //小数年，需转换为月
                                let month = Math.floor(
                                    (maxLengthSchooling - year) * 12
                                );
                                if (month != 0) {
                                    end.setMonth(end.getMonth() + month);
                                }
                                this.endTime=end;
                            }
                        }
                    }
                });
            }
        },
        init() {
            //初始化申请明细
            this.applyForm.defenseTime = null;
            this.applyForm.reasonDesc = null;
            this.applyForm.attachFile = null;
            this.$nextTick(() => {
                this.$refs.applyForm.clearValidate();
            });
            if (this.$refs.uploadBtn) {
                this.$refs.uploadBtn.clearFiles();
                this.fileList = [];
            }
        },
        handleReturn() {
            let changed = false;
            //新增
            if (this.editForm == null) {
                if (
                    Object.keys(this.applyForm).some(
                        key =>
                            this.applyForm[key] != null &&
                            _.trim(this.applyForm[key]) != ""
                    )
                ) {
                    changed = true;
                }
            } else {
                let defenseTime = "defenseTime";
                Object.keys(this.applyForm).forEach(key => {
                    if (
                        key != defenseTime &&
                        this.editForm.hasOwnProperty(key) &&
                        this.applyForm[key] != this.editForm[key]
                    ) {
                        changed = true;
                    }
                });

                if (
                    this.editForm.hasOwnProperty(defenseTime) &&
                    this.applyForm[defenseTime] !=
                        moment(this.editForm[defenseTime]).format("YYYY-MM-DD")
                ) {
                    changed = true;
                }
            }
            if (changed) {
                this.showDialog = true;
            } else {
                this.$emit("close");
            }
        },
        confirmReturn() {
            this.showDialog = false;
            this.$emit("close");
        },
        saveAndClose() {
            this.showDialog = false;
            if (this.showSaveBtn) {
                this.handleSave();
            } else {
                this.handleSubmit();
            }
        },
        postData(isDraft) {
            this.$refs.applyForm.validate(valid => {
                if (!valid) {
                    return;
                }
                this.isDraft = isDraft;
                if (this.fileList.some(f => f.percentage == 0)) {
                    this.$refs.uploadBtn.submit();
                } else {

                    let files = []
                     this.fileList.map(f => {
                        files.push({
                            name:f.name,
                            url: f.url
                        })
                    });
                    this.saveOrSubmit(files);
                }
            });
        },
        handleSave() {
            this.postData(true);
        },
        handleSubmit() {
            this.postData(false);
        },
        handleTime() {
            if (
                this.applyForm.masGrade != null &&
                this.applyForm.masGrade != "" &&
                this.applyForm.masEnrolSeason != null &&
                this.applyForm.masEnrolSeason != ""
            ) {
                getMasTime({
                    masGrade: this.applyForm.masGrade,
                    masEnrolSeason: this.applyForm.masEnrolSeason
                }).then(res => {
                    if (res.code == 200) {
                        this.applyForm.masStartTime = res.data.masStartTime;
                        this.applyForm.masEndTime = res.data.masEndTime;
                    }
                });
            } else {
                this.applyForm.masStartTime = null;
                this.applyForm.masEndTime = null;
            }
        },
        handleUploadExceed() {
            this.$message({
                type: "warning",
                message: "超出文件上传个数"
            });
        },
        handleUploadError(err) {
            this.$message({
                type: "error",
                message: err
            });
        },
        handleUploadSuccess(response, file, fileList) {
            if (fileList.every(file_ => file_.status === "success")) {
                // let files = fileList.map(f => {
                //     return f.response
                //         ? f.response.data[f.name].objectkey
                //         : f.name;
                // });
                let files = []
                for(let key in fileList) {
                if(fileList[key].response && fileList[key].response.data) {
                let res = fileList[key].response.data
                let key0 = Object.keys(res)
                files.push({
                    url: res[key0].objectkey,
                    name: res[key0].fileName
                    })
                } else if(fileList[key].name && fileList[key].url) {
                    files.push({
                    url: fileList[key].url,
                    name: fileList[key].name
                    })
                }
            }
                this.saveOrSubmit(files);
            }
        },
        saveOrSubmit(files) {
            let studentDefenses = [];
            this.students.forEach(student => {
                let params = _.cloneDeep(this.applyForm);
                params.studentId = student.studentId;
                params.saveType = this.editForm ? 0 : 1; //0编辑，1新增
                if (this.editForm) {
                    params.id = this.editForm.id;
                }
                params.defenseType = this.defenseType;
                params.applyType = this.submitType;
                params.trainingLevel = student.trainingLevel;
                params.enrolDate = student.enrolDate;
                params.lengthSchooling = student.lengthSchooling;
                params.attachFile = JSON.stringify(files)
                params.studentName = student.studentName;
                params.maxLengthSchooling = student.maxLengthSchooling;
                params.degreeType = student.degreeType;
                if (
                    student.teacher &&
                    student.teacher.indexOf("(") != -1 &&
                    student.teacher.indexOf(")") != -1
                ) {
                    params.teacher = student.teacher.substring(
                        student.teacher.indexOf("(") + 1,
                        student.teacher.indexOf(")")
                    );
                }
                studentDefenses.push(params);
            });
            let fn = res => {
                if (res.code == 200) {
                    this.$message({
                        type: this.fileSuccessStatus,
                        message: this.isDraft
                            ? this.$t("message.saveSuccess")
                            : this.$t("message.submitSuccess")
                    });
                    this.$emit("success");
                }
            };
            if (this.isDraft) {
                editOralDefense(studentDefenses[0]).then(fn);
            } else {
                this.defenseType == 0
                    ? applyAdvancedOralDefense(studentDefenses).then(fn)
                    : applyDelayedOralDefense(studentDefenses).then(fn);
            }
        },
        handleUploadRemove(file, fileList) {
            this.fileList = fileList;
            this.applyForm.attachFile = fileList.length == 0 ? null : true;
            this.$refs.applyForm.validate();
        },
        handleUploadChange(file, fileList) {
            this.fileList = fileList;
            this.applyForm.attachFile = true;
            this.$refs.applyForm.validate();
        },
        handleFileCheck(rule, value, callback) {
            let hasErr = false;
            //判断文件格式
            let exts = [
                ".doc",
                ".docx",
                ".jpg",
                ".png",
                ".xls",
                ".xlsx",
                ".pdf"
            ];
            for (const file of this.fileList) {
                if (file.status === this.fileSuccessStatus) {
                    continue;
                }
                let fileExtName = file.name
                    .substring(file.name.lastIndexOf("."))
                    .toLocaleLowerCase();
                if (!exts.includes(fileExtName)) {
                    hasErr = true;
                    break;
                }
            }
            if (hasErr) {
                callback(new Error("上传文件格式有错误"));
                return;
            }
            //判断文件大小
            for (const file of this.fileList) {
                if (file.status === this.fileSuccessStatus) {
                    continue;
                }
                if (!(file.size / 1024 / 1024 < 5)) {
                    hasErr = true;
                    break;
                }
            }
            if (hasErr) {
                callback(new Error("上传文件大小不能超过5M"));
                return;
            }
            callback();
        },
        disabledDate(time) {
            // 0提前；1延期
            // 延期答辩且为学校管理员代申请，无时间限制
            if(this.defenseType == 1 && this.submitType == 2) {
                return null
            }
            let currentDate = new Date();
            currentDate.setDate(currentDate.getDate() - 1);
            // 去掉提前答辩时间校验
            if (this.defenseType == 0) {
                return null;
            }
            if (this.endTime) {
                if(this.mayGraduatTime && this.defenseType == 1) {
                // this.applyForm.defenseTime = null
                let beginTime = new Date(this.mayGraduatTime)
                return !(
                    time.getTime() > currentDate.getTime() &&
                    time.getTime() > beginTime.getTime() &&
                    time.getTime() < this.endTime  
                    );
                } else {
                    return !(
                    time.getTime() > currentDate.getTime() &&
                    time.getTime() < this.endTime
                    );
                }
            } else {
                if(this.mayGraduatTime) {
                // this.applyForm.defenseTime = null
                let beginTime = new Date(this.mayGraduatTime)
                return !(
                    time.getTime() > currentDate.getTime() &&
                    time.getTime() > beginTime.getTime()
                    );
                } else {
                return !(time.getTime() > currentDate.getTime());
                }
            }
        }
    }
};
</script>
<style lang="scss" scoped>
#upload-btn {
    button {
        float: left;
    }
    ::v-deep .el-upload {
        display: block;
    }
    ::v-deep .el-upload__tip {
        float: left;
        line-height: 30px;
        margin: 0 0 0 10px;
    }
    ::v-deep .el-upload-list {
        clear: both;
        width: 50%;
    }
}
.msg-tip {
    color: red;
    margin-left: 150px;
    p {
        line-height: 12px;
    }
}
</style>
